#include "eventloop_thread.h"
#include <mutex>


EventLoopThread::EventLoopThread(const ThreadInitCallBack& cb, const std::string& name)
: loop_(nullptr)
, exiting_(false)
, thread_(std::bind(&EventLoopThread::threadFunc, this),name)
, callback_(cb)
, mutex_()
, cond_()
{}


EventLoopThread::~EventLoopThread(){
    exiting_ = true;
    if(loop_ != nullptr){
        loop_->quit();
        thread_.join();
    }
}

// 
EventLoop* EventLoopThread::startLoop(){
    thread_.start();

    EventLoop * loop = nullptr;
    {
        std::unique_lock<std::mutex> lock(mutex_);
        while(loop_ == nullptr){
            cond_.wait(lock);
        }
        loop = loop_;
    }
    return loop;
}

// thread 的执行逻辑
void EventLoopThread::threadFunc(){
    // EventLoop 是在栈空间创建的
    EventLoop loop;             // 创建一个独立的EventLoop  one loop per thread
    if(callback_){
        callback_(&loop);
    }

    {
        std::unique_lock<std::mutex> lock(mutex_);
        loop_ = &loop;
        // 
        cond_.notify_all();

    }

    loop.loop();

    {
        std::unique_lock<std::mutex> lock(mutex_);
        loop_ = nullptr;
    }
}